//
//  EaseApplyManager.m
//  ChatDemo
//
//  Created by 度周末网络-王腾 on 15/12/21.
//  Copyright © 2015年 imac. All rights reserved.
//

#import "EaseApplyManager.h"


@implementation EaseApplyManager


+ (instancetype)shareManager{
    static EaseApplyManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

/**
 *  添加申请消息到本地数据库
 *
 *  @param dictionary
 */
- (void)addNewApply:(NSDictionary *)dictionary
{
    if (dictionary && [dictionary count] > 0) {
        
        NSArray *applyEntitys = [[EaseApplyManager shareManager] loadApplyFromDB];
        
        BOOL isContaintApply = NO;
        for (ApplyEntity *entity in applyEntitys) {
            if ([entity.applicantUsername isEqualToString:[dictionary objectForKey:@"username"]]) {
                isContaintApply = YES;
                break;
            }
        }
        
        if (isContaintApply) return;
        
        ApplyEntity * newEntity= [[ApplyEntity alloc] init];
        newEntity.applicantUsername = [dictionary objectForKey:@"username"];
        newEntity.style = [dictionary objectForKey:@"applyStyle"];
        newEntity.reason = [dictionary objectForKey:@"applyMessage"];
        
        NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
        NSString *loginName = [loginInfo objectForKey:kSDKUsername];
        newEntity.receiverUsername = loginName;
        
        NSString *groupId = [dictionary objectForKey:@"groupId"];
        newEntity.groupId = (groupId && groupId.length > 0) ? groupId : @"";
        
        NSString *groupSubject = [dictionary objectForKey:@"groupname"];
        newEntity.groupSubject = (groupSubject && groupSubject.length > 0) ? groupSubject : @"";
        
        NSString *loginUsername = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
        [[InvitationManager sharedInstance] addInvitation:newEntity loginUser:loginUsername];
    }
}

/**
 *  读取申请消息
 *
 *  @return 消息数组
 */
-(NSArray *)loadApplyFromDB{
    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
    NSString *loginName = [loginInfo objectForKey:kSDKUsername];
    if(loginName && [loginName length] > 0)
    {
        NSArray * applyArray = [[InvitationManager sharedInstance] applyEmtitiesWithloginUser:loginName];
        if (applyArray == nil) {
            return  [[NSArray alloc ] init];
        }
        return applyArray;
    }else{
        return [[NSArray alloc ] init];
    }
}


/**
 *  接受好友申请，并添加好友
 *
 *  @param entiy 好友
 *
 *  @return
 */
- (EMError *)applyAddFriend:(ApplyEntity *)entity
{
    ApplyStyle applyStyle = [entity.style intValue];
    EMError *error;
    if (applyStyle == ApplyStyleJoinGroup){
        [[EaseMob sharedInstance].chatManager acceptApplyJoinGroup:entity.groupId groupname:entity.groupSubject applicant:entity.applicantUsername error:&error];
    }
    else if(applyStyle == ApplyStyleFriend){
        [[EaseMob sharedInstance].chatManager acceptBuddyRequest:entity.applicantUsername error:&error];
    }
    if (!error) {
        NSString *loginUsername = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
        [[InvitationManager sharedInstance] removeInvitation:entity loginUser:loginUsername];
    }
    return error;
}

/**
 *  拒绝好友申请
 *
 *  @param entity 好友
 *
 *  @return
 */
- (EMError *)applyRefuseFriend:(ApplyEntity *)entity
{
    ApplyStyle applyStyle = [entity.style intValue];
    EMError *error;
    if (applyStyle == ApplyStyleGroupInvitation) {
        [[EaseMob sharedInstance].chatManager rejectInvitationForGroup:entity.groupId toInviter:entity.applicantUsername reason:@""];
    }
    else if (applyStyle == ApplyStyleJoinGroup)
    {
        [[EaseMob sharedInstance].chatManager rejectApplyJoinGroup:entity.groupId groupname:entity.groupSubject toApplicant:entity.applicantUsername reason:nil];
    }
    else if(applyStyle == ApplyStyleFriend){
        [[EaseMob sharedInstance].chatManager rejectBuddyRequest:entity.applicantUsername reason:@"" error:&error];
    }
    
    if (!error) {
        NSString *loginUsername = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
        [[InvitationManager sharedInstance] removeInvitation:entity loginUser:loginUsername];
    }
    return error;
}



-(AddFriendStatus)addFriend:(NSString *)buddyName{
    // 已经是好友了
    if ([self didBuddyExist:buddyName]) {
        return DidBuddyExist;
    }
    
    // 已经发送加好友请求
    else if([self hasSendBuddyRequest:buddyName])
    {
        return HasSendBuddyRequest;
    }else{
        
       
        
   
        if ([self sendFriendApplyMessage:buddyName]) {
            return SendBuddyRequestSuccess;
        }else{
            return SendBuddyRequestError;
        }
    }
    
}


- (BOOL)hasSendBuddyRequest:(NSString *)buddyName
{
    NSArray *buddyList = [[[EaseMob sharedInstance] chatManager] buddyList];
    for (EMBuddy *buddy in buddyList) {
        if ([buddy.username isEqualToString:buddyName] &&
            buddy.followState == eEMBuddyFollowState_NotFollowed &&
            buddy.isPendingApproval) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)didBuddyExist:(NSString *)buddyName
{
    NSArray *buddyList = [[[EaseMob sharedInstance] chatManager] buddyList];
    for (EMBuddy *buddy in buddyList) {
        if ([buddy.username isEqualToString:buddyName] &&
            buddy.followState != eEMBuddyFollowState_NotFollowed) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)sendFriendApplyMessage:(NSString *)message
{
    BOOL isSuccess = NO;
    EMError *error;
    if (message && message.length > 0) {
       isSuccess = [[EaseMob sharedInstance].chatManager addBuddy:message message:message error:&error];
    }
    return isSuccess;
}

@end
